import { config } from "../config";
import { ErrorResultProp } from "../props/errorResult";
import { BasicExceptionModel } from "../models/basicException";

const basicException = new BasicExceptionModel();
/**
 * HTTP 服务类
 */
export class HTTP {
  /**
   * 发起 HTTPS 网络请求
   * @param option
   */
  protected request(option: WechatMiniprogram.RequestOption) {
    wx.request({
      url: config.api_base_url + option.url,
      method: option.method,
      header: {
        'content-type': 'application/json',
        'appkey': config.appkey
      },
      data: option.data,
      success: (res) => {
        let code = res.statusCode
        if (code.toString().startsWith('2')) {
          console.log("HTTP.request=>SUCCESS", res)
          option.success && option.success(res);
        } else {
          console.log("HTTP.request=>FAIL", res)
          let errorResult = res.data as ErrorResultProp
          let errorCode = errorResult.error_code;
          basicException.showError(errorCode)
        }
      },
      fail: (err) => {
        console.log("HTTP.request=>FAIL", err)
        basicException.showError(-1)
      }
    })
  }
}